/*
  Copyright (c) 2010 Les Newell. All rights reserved

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program. If not, see <http://www.gnu.org/licenses/>.
*/


//define the module.
DEFINE_MODULE(LED,Module)
//Note the lack of an opening curly bracket.

    //Only use this to expose sockets and parameters. Do most of your
    //initialisastion in Init()
    LED()
    {
        //Expose this parameter to the outside world
        //NOTE: the parmeter name must be a constant.
        //Bad Things will happen if you use a string variable
        AddSocket("LED.FlashRate", &m_rate);
        //set a default rate.
        m_rate = 100;
        m_sequence = 0;


        AddSocket("MaxInt",&m_maxInt);
        AddSocket("MinInt",&m_minInt);
        m_minInt = 32767;
    }

    //A parameter has changed. This happens at bootup if the EEPROM
    //contains valid data and at run-time if the user changes a
    //parameter over the serial link
    virtual void ParamChanged(Socket * param)
    {
        //strictly speaking we don't need to do this check as we
        //only have one parameter
        if (param == &m_rate)
        {
            SetInterval(m_rate);
        }
    }

    //Initialise the module
    //set up hardware etc
    virtual void Init()
    {
        m_flightMode.Connect("FlightMode.Status");
        SetInterval(m_rate);
        SetPriority(5);
        for (int ct=0; ct< LED_OUTPUTS; ct++)
        {
            pinMode (ledPins[ct], OUTPUT);
            digitalWrite(ledPins[ct], LOW);
        }
        m_state = false;
    }

    virtual void Loop(const unsigned long& interval)
    {
        float i = interval / 1000;

        if(i > m_maxInt)
        {
            m_maxInt = i;
        }
        if(i < m_minInt)
        {
            m_minInt = i;
        }
        const byte * outputs = ledSequence[m_flightMode][m_sequence];
        for (int ct=0; ct< LED_OUTPUTS; ct++)
        {
            digitalWrite(ledPins[ct], *outputs);
            outputs++;
        }
        m_sequence ++;
        if (m_sequence >= LED_SEQ_LENGTH)
        {
            m_sequence = 0;
        }
    }

private:
    Parameter16 m_rate;
    bool m_state;
    byte m_sequence;
    Plug8 m_flightMode;

    SocketF m_maxInt;
    SocketF m_minInt;


};

LED g_LED;


